//
//  AppDelegate.swift
//  Weibo10
//
//  Created by male on 15/10/14.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
 
        setupAppearance()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        
        window?.rootViewController = defaultRootViewController
        
        window?.makeKeyAndVisible()
        
        /// 监听通知
        NSNotificationCenter.defaultCenter().addObserverForName(SYLJSwitchRootViewControllerNotification, object: nil, queue: nil) { [weak self] (notification) -> Void in
            let vc = notification.object != nil ? SYLJWelcomeViewController() : MainViewController()
            
            self?.window?.rootViewController = vc
        }
        
        return true
    }
    
    /// 设置全局外观 - 在很多应用程序中，都会在 AppDelegate 中设置所有需要控件的全局外观
    private func setupAppearance() {
        // 修改导航栏的全局外观 － 要在控件创建之前设置，一经设置全局有效
        UINavigationBar.appearance().tintColor = WBAppearanceTintColor
        UITabBar.appearance().tintColor = WBAppearanceTintColor
    }
    deinit {
        // 注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self, name: SYLJSwitchRootViewControllerNotification, object: nil)
    }
}

// MARK: - 界面切换代码
extension AppDelegate {
    
    /// 启动的根视图控制器(
    private var defaultRootViewController: UIViewController {
        
        // 1. 判断是否登录
        if SYLJUserAccountViewModel.sharedUserAccountViewModel.userLogon {
            //1.1 判断用户是不是新版本
            return isNewVersion ? NewFeatureViewController() : SYLJWelcomeViewController()
        }
        // 2. 没有登录返回主控制器
        return MainViewController()
    }
    
    /// 判断是否新版本
    private var isNewVersion: Bool {
        
        // 获得当前的版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)!
        
        // 2. 获取之前的版本
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        // 3. 保存当前版本
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: sandboxVersionKey)
        
        // 4,返回比较的结果
        return version > sandboxVersion
    }
}